/**
 * JAVACC DEMO 1.0
 */
package com.apache.portal.contorller.uct;

import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.passport.common.PassportHelper;
import com.apache.portal.common.PortalPlugin;
import com.apache.portal.common.annotion.BeanFactory;
import com.apache.portal.common.connector.impl.AdapterFactory;
import com.apache.portal.common.restfull.RequestMapping;
import com.apache.portal.common.restfull.ResultFullAnntation;
import com.apache.portal.common.restfull.SupperAction;
import com.apache.tools.DataMap;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.PBOSSOTools;
import com.apache.uct.common.ToolsUtil;
import com.apache.uct.common.entity.User;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.*;

/**
 * description:  用户中心对接Action
 *
 * @author dyhou 创建时间：2016-5-17
 */
@SuppressWarnings("serial")
@ResultFullAnntation(name = "uctHsSystemAction", urlPatterns = { "/res/hs/*"})
public class UctHsSystemAction extends SupperAction {
    protected Logger log = LoggerFactory.getLogger(getClass());
    private PortalPlugin plugin;
    private PortalPlugin netPlugin;
    public void init() {
        plugin = (PortalPlugin) BeanFactory.getInstance().getBeans("uct");
        netPlugin = (PortalPlugin) BeanFactory.getInstance().getBeans("net");
    }

    protected void doInvoke(HttpServletRequest request, HttpServletResponse response,
            String methodType) throws Exception {
        Method method = doInvoke(this.getClass(), request, response, methodType, "");
        if (null != method) {
            Object obj = method.invoke(this, request, response);
            if (!ToolsUtil.isEmpty(obj)) {
                JSONObject array = JSONObject.fromObject(obj);
                this.outputJson(array.toString(), response, request.getParameter("callback"));
            }
        } else {
            gotoErrorPage(request, response, "请求方式有误或请求地址未定义");
        }
    }

    /**
     * 用户登录
     */
    @RequestMapping(value = "login", method = "post")
    protected ResultMsg login(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        ResultMsg msg = null;
        Map<String, String> params = this.getParameterMap(request);
        String if_randCode = ToolsUtil.getInstance().getLocalByKey("config.properties","if_randCode");
        if ("F".equals(if_randCode)) {
            msg = null;
        } else {
            msg = checkRandCode(request, params);
        }
        if (null == msg) {
            params.put("doCode", "U0001");
            msg = (ResultMsg) plugin.doInvoke(request, response,params);
            if ("T".equals(msg.getFlag())) {
                JSONObject jb = JSONObject.fromObject(msg.getMsg());
                Map<String, Object> map = (Map) jb;
                LoginUser loginUser = PBOSSOTools.getLoginUserFromUserCenter(String.valueOf(map.get("userEname")),String.valueOf(map.get("tokenId")));
                if (loginUser != null) {
                    map.put("sysFlag", loginUser.getSysFlag());
                    map.put("auditStatus", loginUser.getUser().getAuditStatus());
                }
                msg.setMsg(JSONObject.fromObject(map).toString());
                request.getSession().setAttribute("loginUser", loginUser);
                log.info("获取的最新【loginUser】"+JSONObject.fromObject(loginUser));

                setMemberInfoToSession(request,loginUser.getUserId(),loginUser.getUserEname());

                setUnitInfoToSession(request);

            }
        }
        log.info("登录结果："+msg.toString());
        return msg;
    }


    /**
     * 修改是否启用 登录验证码校验
     * @param request state:T/F
     * @param response
     * @return
     */
    @RequestMapping(value = "modifyPropRandCode", method = "post")
    protected ResultMsg modifyPropRandCode(HttpServletRequest request, HttpServletResponse response) {
        ResultMsg msg = new ResultMsg("F","操作失败");
        try {
            Map<String, String> params = this.getParameterMap(request);
            String state = StrUtil.doNull(params.get("state"),"T");
            log.info("开始修改配置文件,是否启用 登录验证码校验【"+state+"】.....");
            if (StrUtil.isNotNull(state)){
                String fileNamePath = ToolsUtil.getClassLoaderPath()+"config/config.properties";
                Properties properties = ToolsUtil.getInstance().getProperties(fileNamePath);
//                System.out.println(ToolsUtil.getClassLoaderPath()+fileName);
                OutputStream fos = new FileOutputStream(fileNamePath);
                properties.setProperty("if_randCode",state);
                properties.store(fos,"");
                fos.close();
                msg = new ResultMsg("T","操作成功");
                log.info("config.properties->if_randCode=["+state+"]"+msg.toString());
            }
        } catch (IOException e) {
            msg = new ResultMsg("F","操作失败");
            e.printStackTrace();
        }
        return msg;
    }

    //重置登录信息：如皮肤切换时
    @RequestMapping(value = "resetLoginSession", method = "post")
    protected ResultMsg resetLoginSession(HttpServletRequest request, HttpServletResponse response) {
        ResultMsg msg = new ResultMsg("F","操作失败");
        log.info("开始重置人员login信息到session的内容.....");
        try {
            Map<String, String> params = this.getParameterMap(request);
            LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
            String skinNew = params.get("skin");
            if(StrUtil.isNotNull(skinNew)){
                String skinName = loginUser.getUser().getSkin();
                if(!skinNew.equals(skinName)){
                    User user = loginUser.getUser();
                    user.setSkin(skinNew);
                    loginUser.setUser(user);
                    request.getSession().setAttribute("loginUser", loginUser);
                }
            }
            msg = new ResultMsg("T","操作成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return msg;
    }

    /**
     * 重置单位信息到session的内容
     */
    @RequestMapping(value = "resetUnitSession", method = "post")
    protected ResultMsg resetUnitSession(HttpServletRequest request, HttpServletResponse response) {
        ResultMsg msg = new ResultMsg("F","操作失败");
        log.info("开始重置单位信息到session的内容.....");

        setUnitInfoToSession(request);

        msg = new ResultMsg("T","操作成功");
        return msg;
    }

    /**
     * 重置单位信息到session的内容
     */
    @RequestMapping(value = "resetLoginMemberSession", method = "post")
    protected ResultMsg resetLoginMemberSession(HttpServletRequest request, HttpServletResponse response) {
        ResultMsg msg = new ResultMsg("F","操作失败");
        log.info("开始重置人员member信息到session的内容.....");
        LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
        String userId = loginUser.getUserId();
        String userEname = loginUser.getUserEname();

        setMemberInfoToSession(request,userId,userEname);

        msg = new ResultMsg("T","操作成功");
        return msg;
    }


    //设置会员（人员）member信息到session
    private void setMemberInfoToSession(HttpServletRequest request,String userId,String userEname){
        Map<String, Object> whereMap = new HashMap<String,Object>();
        whereMap.put("hsMember.w_userId",userId);
        ResultEntity entity_hsMember = selectInfoForDatasource("hssystem","s_hsMember","list",whereMap);
        if(entity_hsMember!=null && !ToolsUtil.isEmpty(entity_hsMember.getEntity())){
            List<DataMap> list = (List<DataMap>)entity_hsMember.getEntity();
            if(list.size()>0){
                DataMap loginHsMember = list.get(0);
                String sessionKey = "loginHsMember";
                request.getSession().setAttribute(sessionKey, loginHsMember);
                log.info("获取的最新【"+sessionKey+"】【"+userEname+"】"+JSONObject.fromObject(loginHsMember));
            }
        }
    }

    //设置单位信息到session
    private void setUnitInfoToSession(HttpServletRequest request){
        Map<String, Object> whereMap2 = new HashMap<String,Object>();
        whereMap2.put("orderBy","hsHbzk.create_time desc");
        ResultEntity entity_hsHbzk = selectInfoForDatasource("hssystem","s_hsHbzk","list",whereMap2);
        if(entity_hsHbzk!=null && !ToolsUtil.isEmpty(entity_hsHbzk.getEntity())){
            List<DataMap> list = (List<DataMap>)entity_hsHbzk.getEntity();
            if(list.size()>0){
                DataMap loginHsHbzk = list.get(0);
                String sessionKey = "hsSysUnit";
                request.getSession().setAttribute(sessionKey, loginHsHbzk);
                log.info("获取的最新【"+sessionKey+"】"+JSONObject.fromObject(loginHsHbzk));
            }
        }
    }

    /**
     * description:  用户退出操作（白名单）
     * 使用页面：editUser.jsp
     */
    @RequestMapping(value = "logout", method = "post")
    protected ResultMsg logout(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        Map<String, String> params = this.getParameterMap(request);
        params.put("doCode", "U0000");
        ResultMsg msg = (ResultMsg) plugin.doInvoke(request, response,
                params);//PortalPubFactory.getInstance().getPlugin("uct").doInvoke(request, response, params);
        return msg;
    }

    /**
     * 根据需求修改任何表的字段
     */
    @RequestMapping(value = "dymicSql", method = "post")
    protected Object dymicSql(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        Map<String, String> params = getParameterMap(request);
        params.put("doCode", "dymicSql");
        params.put("resultType", "processSql");
        Map<String, Object> result = new HashMap<String, Object>();
        params = AdapterFactory.getInstance()
                .getReqParamForBefor("setReqParam", params, request, response);//前拦截
        String execptionMsg = String.valueOf(params.get("execptionMsg"));
        if (StrUtil.isNotNull(execptionMsg)) {
            ResultMsg msg = new ResultMsg("F", execptionMsg);
            return msg;
        }
        ResultEntity entity = (ResultEntity) netPlugin.doInvoke(request, response,
                params);// PortalPubFactory.getInstance().getPlugin("net")
        //.doInvoke(request, response, params);
        result.put("flag", String.valueOf(entity.getResult()));
        result.put("msg", String.valueOf(entity.getMessage()));
        result.put("ids", entity.getEntity());
        return result;
    }



    /**
     * description:  验证验证码
     */
    private ResultMsg checkRandCode(HttpServletRequest request, Map<String, String> params) {
        ResultMsg msg = null;
        String ifRandCode = request.getParameter("randCodeMark");
        if (ToolsUtil.isNotNull(ifRandCode))
            return null;
        String randCode = String.valueOf(request.getSession().getAttribute("randCode"));
        if (ToolsUtil.isNull(randCode))
            return null;
        if ((StrUtil.isNull(params.get("rand")))) {
            msg = new ResultMsg("F", "验证码不能为空");
            return msg;
        }
        if (!params.get("rand").equals(randCode)) {
            msg = new ResultMsg("F", "验证码错误");
            return msg;
        }
        return msg;
    }

    private void setLoginUser(HttpServletRequest request) {
        LoginUser loginUser = PBOSSOTools.getLoginUser(request);
        if (null == loginUser) {
            try {
                String cookieValue = PassportHelper.getInstance().getCurrCookie(request);
                String value = PassportHelper.getInstance().getCurrCookie(request, "_uc.sso");
                if (StrUtil.isNotNull(cookieValue) && StrUtil.isNotNull(value)) {
                    //value = DesUtils.getInstance().decrypt(value);
                    loginUser = PBOSSOTools.getLoginUserFromUserCenterSso(cookieValue);
                    if (null != loginUser) {
                        request.getSession().setAttribute("loginUser", loginUser);
                    }
                }
            } catch (Exception e) {
            }
        }
    }


}
